package com.octnote.service;

import com.octnote.domain.contacts.Contacts;
import com.octnote.domain.user.User;
import com.octnote.repository.ContactsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by leohehe on 2017/6/16.
 */
@Service
public class ContactsServiceImpl implements ContactsService{
    private UserService userService;
    private ContactsRepository contactsRepository;

    @Autowired
    public ContactsServiceImpl(ContactsRepository contactsRepository, UserService userService){
        this.userService = userService;
        this.contactsRepository = contactsRepository;
    }

    @Override
    public Page<Contacts> getContacts(String searchPhrase, Pageable p) {
        return contactsRepository.findByUserIdContaining(searchPhrase, p);
    }

    @Override
    public List<Contacts> syncContacts(List<Contacts> contactsList) {
        //用联系人的电话号码去与APP用户对比，发现相同的则标记为APP用户联系人
        for(Contacts contacts : contactsList){
            String contactMobile = contacts.getContactMobile();
            //根据电话号码查询用户
            User user = userService.getUserByMobile(contactMobile);
            if(user != null){
                contacts.setImage(user.getImage());
                contacts.setOctopusUser(true);
            }
        }
        contactsRepository.save(contactsList);
        return contactsList;
    }
}
